<?php





namespace app\shop\model;



use app\crm\model\FollowRecord;

use app\admin\model\Common;

use Kingdee\Kingdee;

use think\facade\Db;

use think\model\concern\SoftDelete;

use app\common\traits\ActionRecordTrait;

use app\shop\model\AddOrderLog;



/**

 * 订单模型

 * @package app\shop\model

 * @author LIU

 * @create 2021-10-01

 */

class Order extends Common

{

    use ActionRecordTrait;



    /**

     * 表名

     * @var string

     */

    protected $name = 'shop_order';

    protected $defaultSoftDelete = 0;



    /**

     * 获取sku信息

     * @return \think\model\relation\hasOne

     * @author SL

     * @create 2021-05-27 15:04

     */

    public function orderGoods()

    {

        return $this->hasOne(Goods::class,'id');

    }









    /**

     * 获取sku信息

     * @return \think\model\relation\hasOne

     * @author SL

     * @create 2021-05-27 15:04

     */

    public function getHouseList($request)

    {

        try {



            $request = $this->fmtRequest($request);

            $map     = $request['map'] ?? [];

            if(!$map){

                $this->error = '请传入会员id';

                return [];

            }

            $shop_id = $map['shop_id'] ?? 0;

            if(!$shop_id){

                $this->error = '请传入门店id';

                return [];

            }

            $market_id=Db::name('shop')->where('shop_id',$shop_id)->value('market_id');

            $list=Db::name('house_code')->where('market_id',$market_id)->field('id,house_code_name,house_code')->select();

            $data              = [];

            $data['list']      = $list ?? [];

            return $data;

        }catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];

        }



    }





    /**

     * 获取销售政策列表

     * @return array

     * @author SL

     * @create 2021-06-1

     */

    public function getSaleList()

    {

        try {

            $list = Db::name('policy')->where('status',1)->select();

            $data              = [];

            $data['list']      = $list ?? [];

            return $data;

        }catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];

        }

    }













    /**

     * 获取订单列表

     * @param  array $request 请求参数

     * @return array

     * @author SL

     * @create 2021-06-1

     */

    public function getDataList($request)

    {

        try {

            $userId  = $request['user_id'] ?? 0;

            $shopIds= $request['shopIds'] ?? '';

            $request = $this->fmtRequest($request);



            $map     = $request['map'] ?? [];

            $where   = [];

            $id = isset($map['id']) && $map['id'] ? $map['id'] : [];

            if ($id) {

                if (!is_array($id)) {

                    $id = [$id];

                }

                array_push($where, ['o.id', 'in', $id]);

            }

            array_push($where, ['o.status', '<>', 4]);//排查已作废的

            $uid      = isset($map['uid']) && $map['uid'] ? trim($map['uid']) : ''; // 会员id

            $shop_id      = isset($map['shop_id']) && $map['shop_id'] ? trim($map['shop_id']) : ''; // 门店id

            $noValue      = isset($map['no_value']) && $map['no_value'] ? trim($map['no_value']) : ''; // 单号

            $consignee = isset($map['consignee']) && $map['consignee'] ? trim($map['consignee']) : ''; // 客户名称

            $status       = isset($map['status']) && intval($map['status']) ? intval($map['status']) : '-1'; // 订单状态

            $start_time = isset($map['start_time']) && $map['start_time'] ? strtotime(date($map['start_time'])) : 0;

            $end_time = isset($map['end_time']) && $map['end_time'] ? strtotime(date($map['end_time'] . ' 23:59:59')) : 0;

            $business_type    = isset($map['business_type']) && intval($map['business_type']) ? intval($map['business_type']) : 0; // 订单状态

            $order_type       = isset($map['order_type']) && intval($map['order_type']) ? intval($map['order_type']) : 0; // 订单状态

            $low_total = isset($map['low_total']) && $map['low_total'] ? $map['low_total']: 0;//销售金额区间搜索最小值

            $large_total =  isset($map['large_total']) && $map['large_total'] ? $map['large_total']: 0;//销售金额区间搜索最大值

            $shop_name = isset($map['shop_name']) && $map['shop_name'] ? trim($map['shop_name']) : ''; // 门店名称

            // 获取客户数据权限 的客户名称

            if ($shopIds)

            {

                array_push($where, ['o.shop_id', 'in', $shopIds]);

            }



            if ($uid)

            {

                //会员id搜索

                array_push($where, ['o.uid', '=', $uid]);

            }

            if ($shop_id)

            {

                //门店id搜索

                array_push($where, ['o.shop_id', '=', $shop_id]);

            }



            if ($shop_name)

            {

                //门店名称搜索

                array_push($where, ['o.shop_name', 'like', '%'.$shop_name.'%']);

            }

            if ($consignee) {

                // 客户名称搜索

                array_push($where, ['o.consignee', 'like', '%'.$consignee.'%']);

            }

            if ($status != -1) {

                array_push($where, ['o.status', '=', $status]);

            }

            if ($noValue) {

                array_push($where, ['o.order_no', '=', $noValue]);

//                $noType == 2 && array_push($where, ['o.king_num', '=', $noValue]);

//                $noType == 3 && array_push($where, ['o.king_send_no', '=', $noValue]);

//                $noType == 4 && array_push($where, ['o.king_sale_no', '=', $noValue]);

            }





            // 时间

            if($start_time && $end_time)

            {

                array_push($where, ['o.deal_time', 'between', "$start_time,$end_time"]);

            }



            if ($business_type)

            {

                //业务类型搜索

                array_push($where, ['o.business_type', '=', $business_type]);

            }

            if ($order_type)

            {

                //订单类型搜索

                array_push($where, ['o.order_type', '=', $order_type]);

            }



            if ($low_total && !$large_total)

            {

                array_push($where, ['o.order_amount', 'egt', $low_total]);

            }

            if (!$low_total && $large_total)

            {

                array_push($where, ['o.order_amount', 'elt', $large_total]);

            }

            if ($low_total && $large_total)

            {

                array_push($where, ['o.order_amount', 'between', "$low_total,$large_total"]);

            }

            $sqlQuery = $this->alias('o')

                ->where($where);

            $dataCount  = $sqlQuery->count();

            $sum_amount=0;



            if ($dataCount) {

                $sum_amount  = $sqlQuery->sum('o.order_amount');

                // 订单列表

                $field = ['o.id', 'o.order_no','o.is_lock','o.business_type','o.order_type','o.king_status', 'o.sale_name', 'o.consignee',

                    'o.goods_price','o.order_amount','o.status','o.shop_name','o.create_time','o.shop_id','o.deal_time','c.king_no'];

                $list = $sqlQuery->field($field)

                    ->join('customer c', 'o.uid = c.id')

                    ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])

                    ->order('id DESC')

                    ->select()->toArray();

                if ($list) {

                    foreach($list as &$v){

                        $v['order_type']=$v['order_type']==1?'新单':'补单';

                        $v['business_type']=$v['business_type']==1?'疤痕':'项目';

                        $v['deal_time']=date('Y-m-d', $v['deal_time']);

                        switch ($v['king_status']) {

                            case '1':

                                $v['king_status_msg'] = '已下推';

                                break;

                            case '2':

                                $v['king_status_msg'] = '下推失败';

                                break;

                            case '5':

                                $v['king_status_msg'] = '登录失败';

                                break;

                            default:

                                $v['king_status_msg'] = '暂未下推';

                                break;

                        }

                        switch ($v['status']) {

                            case '1':

                                $v['status_msg'] = '已支付';

                                break;

                            case '2':

                                $v['status_msg'] = '已下推';

                                break;

                            case '3':

                                $v['status_msg'] = '已评价';

                                break;

                            case '4':

                                $v['status_msg'] = '已作废';

                                break;

                            default:

                                $v['status_msg'] = '待审核';

                                break;

                        }

                    }

                }

            }



            $permission = get_user_permission_menu($userId,'order_list_tag');



            $data              = [];

            $data['menu_list'] = $permission ? $permission : [];

            $data['list']      = $list ?? [];

            $data['dataCount'] = $dataCount ?? 0;

            if($start_time && $end_time){

                $data['sum_amount'] = $sum_amount ?? 0;

            }

            return $data;

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];

        }

    }



    /**

     * 订单主要详情

     * @param array $request

     * @return array

     * @author SL

     * @create 2021-06-02

     */

    public function getDataDetail($request)

    {

        try {

            $id = $request['order_id'] ?? 0;

            if(!$id){

                $this->error = '请传入订单id';

                return [];

            }

            $detail = [];

            $field = ['id,consignee,operator_name,sale_name,shop_name,business_type,order_type,income_type,status,is_pay,total_amount,discount_amount,

            pay_amount,gift_amount,order_amount,coupon_id,coupon_name,is_experience,is_outreach,outreahc_name,is_introduction,introduction_name,

            deal_time,create_time,king_push_time,king_status,shop_market','coupon_id','coupon_name','sales_name','settlement_name','market_name','pay_time','king_sale_no','delivery_name',

            'experience_id,outreahc_id,introduction_id'
            ];

            $detail = $this->where('id',$id)->field($field)->find();

            if($detail){

                // 时间转化

                $detail['pay_time'] = $detail['pay_time'] ? date('Y-m-d H:i:s', $detail['pay_time']) : '';

                $detail['king_push_time'] = $detail['king_push_time'] ? date('Y-m-d H:i:s', $detail['king_push_time']) : '';

                $detail['complete_time'] = $detail['complete_time'] ? date('Y-m-d H:i:s', $detail['complete_time']) : '';

                $detail['cancel_time'] = $detail['cancel_time'] ? date('Y-m-d H:i:s', $detail['cancel_time']) : '';

                $detail['business_type']    = $detail['business_type'] == 1 ? "疤痕":'项目';

                $detail['order_type']    = $detail['order_type'] == 1 ? "新单":'补单';

                $detail['deal_time'] = $detail['deal_time'] ? date('Y-m-d', $detail['deal_time']) : '';

                switch ($detail['status']) {

                    case '1':

                        $detail['status_msg'] = '已支付';

                        break;

                    case '2':

                        $detail['status_msg'] = '已下推';

                        break;

                    case '3':

                        $detail['status_msg'] = '已评价';

                        break;

                    case '4':

                        $detail['status_msg'] = '已作废';

                        break;

                    default:

                        $detail['status_msg'] = '待支付';

                        break;

                }

            }

            else{

                $this->error = '订单不存在';

                return false;

            }

            $userId  = $request['user_id'] ?? 0;

            $permission = get_user_permission_menu($userId,'order_list_tag');

            $detail['menu_list'] = $permission ? $permission : [];

            return $detail;

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];

        }

    }


	/*
	* 修改订单--销售出库单
	* @create 2022-04-19

	*/

	public function updateDataDetail($request)
	{
	    $order = $this->find($request['id']);
	    if(empty($order))//验证订单
	       {
	         $this->error='订单不存在';
	         return false;
	       }
	    if(empty($request['is_experience']))//是否体验
	    {
	        $order->is_experience = 0;
	        $order->experience_id = 0;
	        $order->experience_name = "";
	    }else{
	        if(empty($request['experience_id']))
	        {
	            $this->error='未选择体验人';
	            return false;
	        }else{
	            $staff=Db::name('shop_person')->field('id,name')->where('id',$request['experience_id'])->find();
	            if(empty($staff))
	            {
	                $this->error='体验人不存在';
	                return false;
	            }else{
	                $order->is_experience = $request['is_experience'];
	                $order->experience_id = $request['experience_id'];
	                $order->experience_name = $staff['name'];
	            }
	        }
	    }

	    if(empty($request['is_introduction']))//是否转介绍
	    {
	        $order->is_introduction = 0;
	        $order->introduction_id = 0;
	        $order->introduction_name = "";
	    }else{
	        if(empty($request['introduction_id']))
	        {
	            $this->error='未选择转介绍人';
	            return false;
	        }else{
	            $staff=Db::name('shop_person')->field('id,name')->where('id',$request['introduction_id'])->find();
	            if(empty($staff))
	            {
	                $this->error='转介绍人不存在';
	                return false;
	            }else{
	                $order->is_introduction = $request['is_introduction'];
	                $order->introduction_id = $request['introduction_id'];
	                $order->introduction_name = $staff['name'];
	            }
	        }
	    }


	    if(empty($request['is_outreach']))//是否外部联系
	    {
	        $order->is_outreach = 0;
	        $order->outreahc_id = 0;
	        $order->outreahc_name = "";
	    }else{
	        if(empty($request['outreahc_id']))
	        {
	            $this->error='未选择外部联系人';
	            return false;
	        }else{
	            $staff=Db::name('shop_person')->field('id,name')->where('id',$request['outreahc_id'])->find();
	            if(empty($staff))
	            {
	                $this->error='外部联系人不存在';
	                return false;
	            }else{
	                $order->is_outreach = $request['is_outreach'];
	                $order->outreahc_id = $request['outreahc_id'];
	                $order->outreahc_name = $staff['name'];
	            }
	        }
	    }

	    $order->order_type=$request['order_type'];
        try{
            if($order->business_type != $request['business_type'])
            {
                $balanceAdd = Db::name('customer_balance')->where([
                    ['customer_id','=',$order->uid],
                    ['balance_category_id','=',$order->business_type]
                ])->find();
                $balanceRED = Db::name('customer_balance')->where([
                    ['customer_id','=',$order->uid],
                    ['balance_category_id','=',$request['business_type']]
                ])->find();
                Db::name('customer_balance')->where([
                    ['customer_id','=',$order->uid],
                    ['balance_category_id','=',$order->business_type]
                ])->update([
                    'money'=>$balanceAdd['money']+$order->pay_amount,
                    'complimentary_money'=>$balanceAdd['complimentary_money']+$order->gift_amount
                ]);
                Db::name('customer_balance')->where([
                    ['customer_id','=',$order->uid],
                    ['balance_category_id','=',$request['business_type']]
                ])->update([
                    'money'=>$balanceRED['money']-$order->pay_amount,
                    'complimentary_money'=>$balanceRED['complimentary_money']-$order->gift_amount
                ]);
            }
            $order->business_type=$request['business_type'];
            $res=$order->save();
        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];

        }
	    if($res)
	    {
	        return ['msg'=>"更新完毕",'code'=>200];
	    }else{
	        $this->error='更新失败';
	        return false;
	    }
	}


    /**

     * 订单商品详情

     * @param array $request

     * @return array

     * @author SL

     * @create 2021-06-02

     */

    public function getGoodsDataDetail($request)

    {

        try {

            $id = $request['order_id'] ?? 0;

            if(!$id){

                $this->error = '请传入订单id';

                return [];

            }

            $detail = [];

            $list =[];

            $detail = Db::name('shop_order')->field('id')->where('id',$id)->find();



            if($detail)

            {

                // 订单商品

                $detail['goodsList'] = [];

                $og_field = ['id as order_goods_id', 'goods_id', 'number', 'goods_price', 'pay_price', 'goods_name', 'kingdee_code',  'unit_code',  'unit_name', 'category_id',  'pay_price * number AS order_goods_price','is_project','project_type','service_number','start_time','end_time','house_code','house_code_name','is_coupon_goods'];

                $list = Db::name('shop_order_goods')

                    ->where('order_id', $id)

                    ->order('id DESC')

                    ->field($og_field)->select()->toArray();

                foreach ($list as $key => $value)

                {

                    $list[$key]['start_time'] = date("Y-m-d",$value['start_time']);

                    $list[$key]['end_time'] = date("Y-m-d",$value['end_time']);

                }

            }

            else{

                $this->error = '订单不存在';

                return false;

            }



            if ($list) {

                $detail['goodsList'] = $list;

            }

            return $detail;

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];

        }

    }



    /**

     * 订单验证公共方法

     * @param  array $data 请求参数

     * @return bool

     * @author SL

     * @create 2021-06-03

     */

    function orderAdd($data)

    {

        $result=['status'=>1,'error'=>''];

        if (isset($data['is_outreach']))

        {

            if (!isset($data['outreahc_id']))

            {

                $result['error']='外联选是时，外联人必须选择';

                $result['status']=0;

                return $result;

            }

        }



        if (isset($data['is_introduction']))

        {

            if (!isset($data['introduction_id']))

            {

                $result['error']='转介绍选是时，转介绍人必须选择';

                $result['status']=0;

                return $result;

            }

        }

        return $result;



    }



    /**

     * 创建订单

     * @param  array $request 请求参数

     * @return bool

     * @author SL

     * @create 2021-06-03

     */

    public function addData($request)

    {

        try {

            $validate = new \app\shop\validate\Order();

            if (!$validate->scene('create')->check($request)) {

                $this->error = $validate->getError();

                return false;

            }

        }catch (\Exception $e) {

            $this->error = $e->getMessage();

            return false;

        }

        $result=$this->orderAdd($request);

        if (!$result['status'])

        {

            $this->error = $result['error'];

            return false;

        }



        Db::startTrans();

        try {

            $time = time();

            $orderGoodsListArr = $request['goodsList'];

            $goods_ids = array_column($orderGoodsListArr, 'id');

            $where = [

                ['id','in', $goods_ids]

            ];

            $field = 'id, kingdee_code';

            $goodsInfo = Db::name('shop_goods')->where($where)->field($field)->select()->toArray();

            $goodsInfo = array_column($goodsInfo, null, 'id');

            // 支付总金额

            $payAmount = [];

            $error = '';

            $goods_price= [];

            $shop=Db::name('shop')->where('shop_id',$request['shop_id'])->field('type,keycode')->find();//判断直营 加盟

            //直营店门店编码 发货组织编码 销售组织编码必传

            if ($shop['type'] == 1)

            {

                if (!$shop['keycode']|| !isset($request['sales_organization'])|| !$request['sales_organization'] || !isset($request['settlement_organization'])|| !$request['settlement_organization'])

                {

                    $this->error = '直营店门店编码或发货组织编码或销售组织编码不存在，请联系总部解决';

                    return false;

                }

            }

            $order_experience=0;

            foreach ($orderGoodsListArr as $key => $value) {

                //服务类型判断

                if (isset($value['is_project']) && $value['is_project']==2 && !in_array($value['id'],[170,171]))

                {

                    if (!isset($value['project_type']))

                    {

                        $this->error = '请选择服务类型';

                        return false;

                    }else{

                        if ($value['project_type'] == 1)

                        {

                            if (!isset($value['service_number']) || empty($value['service_number']))

                            {

                                $this->error = '服务卡选次数必填';

                                return false;

                            }

                        }else

                        {

                            if (!isset($value['start_time']) || !isset($value['end_time'])||empty($value['start_time'])||empty($value['end_time']))

                            {

                                $this->error = '服务周期必填';

                                return false;

                            }

                        }



                    }

                }

                if(!isset($value['number']) || empty($value['number']))

                {

                    $this->error = '请填写销售数量';

                    return false;

                }



                if(!isset($value['house_code']) || empty($value['house_code']))

                {

                    $this->error = '请选择仓库';

                    return false;

                }

                if(!isset($value['category_id']) || empty($value['category_id']))

                {

                    $this->error = '商品分类必传';

                    return false;

                }



                if(strcmp($value['kingdee_code'],$goodsInfo[$value['id']]['kingdee_code']) !=0)

                {

                    $error .= '商品【' . $value['name'] . '】金蝶编码有变动；';

                }

                if (in_array($value['kingdee_code'],['101.12.026','101.12.042','101.12.045']))

                {

                    $order_experience=1;

                }

                if (!$value['is_coupon_goods'])

                {

                    $payAmount[] = bcmul($value['pay_price'], $value['number'], 2);

                    $goods_price[] = bcmul($value['goods_price'], $value['number'], 2);

                }

            }

            if($error)

            {

                $this->error = $error;

                return false;

            }

            $goods_price=array_sum($goods_price);

            $discount_amount=isset($request['discount_amount']) ? $request['discount_amount'] : 0;

            $total_amount = bcadd(array_sum($payAmount),0,2);

            $money=bcadd(bcadd($request['pay_amount'],$request['gift_amount'],2),$discount_amount,2);

            //调取相关接口，处理实收金额 赠送金额

            //判断金额

            if ($total_amount != $money || $total_amount !=$request['total_amount'])

            {

                $this->error = '订单金额不正确';

                return false;

            }

            $operator_name= Db::name('admin_user')->where(['id' => $request['operator_id']])->value('realname');

            // 验证

            $data = [

                'uid'               => trim($request['uid']), // 客户

                'consignee'         => trim($request['consignee']), // 收货人

                'order_no'          => $this->getOrderNo(), // 订单号

                'sale_id'           => $request['sale_id'], // 销售员id

                'sale_name'           => trim($request['sale_name']), // 销售员姓名

                'shop_id'           => $request['shop_id'], // 门店id

                'shop_name'           => trim($request['shop_name']), // 门店名称

                'operator_id'       => $request['operator_id'],//制单员id

                'operator_name'       => $operator_name,//制单员姓名

                'create_time'       => $time, // 创建时间

                'deal_time'         => strtotime($request['deal_time']), // 成交日期

                'goods_price'      => $goods_price, // 订单标准金额

                'total_amount'      => $total_amount, // 订单总金额

                'pay_amount'        => isset($request['pay_amount']) ? $request['pay_amount'] : 0, // 实收本金

                'discount_amount'   =>$discount_amount, // 订单优惠金额

                'gift_amount'        => isset($request['gift_amount']) ? $request['gift_amount'] : 0, // 实收赠金

                'order_amount'      => isset($request['order_amount']) ? $request['order_amount'] : 0, // 订单优惠金额

                'is_experience'     => $request['is_experience'], // 是否体验 0否 1是

                'experience_id'       => isset($request['experience_id']) ? $request['experience_id'] : 0, // 体验人id

                'experience_name'       => isset($request['experience_name']) ? $request['experience_name'] : '', // 体验人姓名

                'is_outreach'       => $request['is_outreach'], // 是否外联 0否 1是

                'coupon_id'       => isset($request['coupon_id']) ? $request['coupon_id'] : 0, // 优惠券id

                'coupon_name'       => isset($request['coupon_name']) ? $request['coupon_name'] : 0, // 优惠券id

                'outreahc_id'       => isset($request['outreahc_id']) ? $request['outreahc_id'] : 0, // 外联人id

                'outreahc_name'       => isset($request['outreahc_name']) ? $request['outreahc_name'] : '', // 外联人姓名

                'is_introduction'       => $request['is_introduction'], // 是否转介绍 0否 1是

                'introduction_id'       => isset($request['introduction_id']) ? $request['introduction_id'] : 0, // 转介绍人id

                'introduction_name'       => isset($request['introduction_name']) ? $request['introduction_name'] : '', // 转介绍人姓名

                'description'                => isset($request['description']) ? $request['description'] : '', // 订单描述

                'order_type'                => $request['order_type'], // 订单类型 1新单 2补单

                'business_type'                => $request['business_type'], // 业务类型 1项目 2疤痕

				'income_type'                => $request['income_type'], // 收入类型 1 服务（各类疗程卡项及疗程卡项赠送产品）2 产品销售（单独付费购买产品）3 医美收入

                'sales_policy'                => isset($request['sales_policy'])? $request['sales_policy'] : '', // 销售政策编码

                'market_id'       => isset($request['market_id']) ? $request['market_id'] : 0, // 市场id

                'market_name'       => isset($request['market_name']) ? $request['market_name'] : 0, // 市场名称

                'sales_organization'       => isset($request['sales_organization']) ? $request['sales_organization'] : 0, // 销售组织编码

                'sales_name'       => isset($request['sales_name']) ? $request['sales_name'] : '', // 销售组织名称

                'settlement_organization'       => isset($request['settlement_organization']) ? $request['settlement_organization'] : 0, // 结算组织编码

                'settlement_name'       => isset($request['settlement_name']) ? $request['settlement_name'] : '', // 结算组织名称

                'order_experience'       =>$order_experience ,//订单是否有体验商品

                'delivery_name'       => isset($request['delivery_name']) ? $request['delivery_name'] : '', // 发货部门名称

                'delivery_king'       => isset($request['delivery_king']) ? $request['delivery_king'] : '', // 发货部门编码

            ];

            $order = $this->create($data);

            $member_products = 0;

            $serviceDataAll = [];

            if ($order) {

                foreach ($orderGoodsListArr as $k => $v) {

                    $orderGoodsList[$k]['order_id'] = $order->id;

                    $orderGoodsList[$k]['create_time'] = $time;

                    $orderGoodsList[$k]['goods_id'] = $v['id'];

                    $orderGoodsList[$k]['goods_name'] = $v['name'];

                    $orderGoodsList[$k]['kingdee_code'] = $v['kingdee_code'];

                    $orderGoodsList[$k]['goods_price'] = $v['goods_price'];

                    $orderGoodsList[$k]['pay_price'] = $v['pay_price'];

                    $orderGoodsList[$k]['spec_name'] = $v['spec_name'];

                    $orderGoodsList[$k]['unit_code'] = $v['unit_code'];

                    $orderGoodsList[$k]['unit_name'] =  isset($v['unit_name']) ? $v['unit_name'] : '';;

                    $orderGoodsList[$k]['number'] = $v['number'];

                    $orderGoodsList[$k]['desc'] = $v['desc'];

                    $orderGoodsList[$k]['is_project'] = $v['is_project'];//是否服务 1 是 2否

                    $orderGoodsList[$k]['category_id'] =  $v['category_id'];

                    $orderGoodsList[$k]['is_coupon_goods'] = isset($v['is_coupon_goods']) ? $v['is_coupon_goods'] : 0;//是否优惠券商品 0否 1是

                    $orderGoodsList[$k]['project_type'] = isset($v['project_type']) ? $v['project_type'] : 0;//服务类型 1 按次 2按天

                    $orderGoodsList[$k]['service_number'] = isset($v['service_number']) ? $v['service_number'] : 0;//服务次数

                    $orderGoodsList[$k]['start_time']     = isset($v['start_time']) ? strtotime($v['start_time']) : 0;

                    $orderGoodsList[$k]['end_time'] = isset($v['end_time']) ? strtotime($v['end_time']) : 0;

                    $orderGoodsList[$k]['is_gift'] = isset($v['is_gift']) ? $v['is_gift'] : 0;

                    $orderGoodsList[$k]['house_code'] = $v['house_code'];

                    $orderGoodsList[$k]['coupon_type'] = isset($v['coupon_type']) ? $v['coupon_type'] : 0;//优惠券类型

                    $orderGoodsList[$k]['house_code_name'] = isset($v['house_code_name']) ? $v['house_code_name'] : '';

                    // 新加的代码

                    if($v['kingdee_code'] == '101.12.099'){

                        $member_products += $orderGoodsList[$k]['number'];

                        // 入会即时发券 --------start---------
                        $time = time();
                        $customer_id = $request['uid'];

                        $card_id = ['101','102','103','104','105','106','107','108','109','110'];

                        $customerList = Db::name('customer')->where('id','=',$customer_id)->select();


                        $cardList = array();

                        if(floor($customerList[0]['consumption'])<'5000')
                        {
                            $this->error = '客户累计消费金额不足5000元';
                            return false;
                        }

                        if(floor($customerList[0]['consumption'])>='5000' && floor($customerList[0]['consumption'])<'15000'){
                            array_push($cardList,'101','102');
                        }

                        if(floor($customerList[0]['consumption'])>='15000' && floor($customerList[0]['consumption'])<'50000'){
                            array_push($cardList,'103','104','105','106');
                        }

                        if(floor($customerList[0]['consumption'])>='50000'){
                            array_push($cardList,'107','108','109','110');
                        }


                        $i=0;
                        $r=0;

                        $provideCustomerList = array();


                        $repeatArr = array();

                        // echo "<pre>";
                        // print_r($cardList);
                        // echo "</pre>";



                        foreach ($cardList as $k1 => $v1) {
                            $isSend = Db::name('coupon_provide_customer')->where('customer_id','=',$customer_id)->where('coupon_id','in',$card_id)->select()->toArray();

                            if(empty($isSend)){

                                $provideCustomerList[$i]['coupon_id'] = $v1;
                                $provideCustomerList[$i]['create_time'] = $time;
                                $provideCustomerList[$i]['customer_id'] = $customer_id;
                                $provideCustomerList[$i]['staus'] = '0';
                                $i++;

                            }else{
                                $repeatArr[$r]['coupon_id'] = $v1;
                                $r++;
                            }


                        }

                        if(!empty($provideCustomerList)){
                            Db::name('coupon_provide_customer')->insertAll($provideCustomerList);
                        }


                        // 入会即时发券 --------end---------

                    }

                    // print_r($v);

                    if($v['is_project'] == 2 && $v['id'] != 170 && $v['id'] != 171){

                        for($i=1;$i<=$orderGoodsList[$k]['number'];$i++){

                            $oneService['name']    = $orderGoodsList[$k]['goods_name'];  //服务名称

                            $oneService['num']     = $orderGoodsList[$k]['service_number'];   // 必填--服务类型：1按期2按次

                            $oneService['shop_id'] = $data['shop_id'];    // 店铺id

                            $oneService['customer_id']  = $data['uid'];   // 必填--客户id

                            $oneService['service_type'] = $orderGoodsList[$k]['project_type']==1?2:1;   // 必填--服务类型：1按期2按次

                            $oneService['start_time']   = $orderGoodsList[$k]['start_time'];    // 类型为1是必填--服务开始时间

                            $oneService['end_time']     = $orderGoodsList[$k]['end_time'];      // 类型为1是必填--服务开始时间

                            $oneService['experience']   = $data['is_experience'];     // 0否1是 是否体验

                            $oneService['kk_user_id']   = $data['sale_id'];     // 开卡人id

                            $oneService['kk_money']     = $data['total_amount'];       // 开卡金额

                            $oneService['goods_id']     = $orderGoodsList[$k]['goods_id'];       // 开卡金额

                            $oneService['category_id']  = $orderGoodsList[$k]['category_id'];       // 开卡金额

                            array_push($serviceDataAll,$oneService);

                        }

                    }

                }

                Db::name('shop_order_goods')->insertAll($orderGoodsList);



                // 添加操作记录

                $goods_name = array_column($orderGoodsList, 'goods_name');

                $goods_name_str = implode('|', $goods_name);

                $content = '创建订单：【'. $operator_name . '】创建了【' . $request['consignee'] . '】' . '的订单，订单号：【' . $data['order_no'] . '】，商品：【' . $goods_name_str . '】';

                $code = [];

                $code = $data;

                $code['orderGoodsList']  = $orderGoodsList;

                $this->addActionRecord($request['operator_id'],'shop_order_create',$order->id,$content,'shop','order',json_encode($code));

                // 处理客户的余额 //

                //存储客户的最后消费时间

                $updateCusetomer = [

                    'final_consumption' => time(),

                    'final_consumption_money' => $data['total_amount'],

                ];

                Db::name('customer')->where('id','=',$data['uid'])->update($updateCusetomer);

                $customerModel = new \app\crm\model\Customer();

                $customer_id   = $data['uid'];    // 客户的id

                $balanceData   = [                // 余额变更数据集

                    'change_type'  => 2,      // 变动类型 1:增加 2:减少

                    'change_money' => $data['pay_amount'],      // 变更的本金

                    'complimentary_money' => $data['gift_amount'],  // 变更的赠金

                    'balance_category_id' => $data['business_type'] // 变更的余额的类型 1:疤痕 2:项目

                ];

                $newOrderData  = [   // 新单变更数据集

                    // 'cj_time'  => ($data['type']==3 && $data['order_type']==1 && $total_amount>500)?$data['deal_time']:0,     // 成交时间-时间戳

                    // 'cj_money'    => $total_amount,    // 成交金额

                    // 'cj_order_id' => $order->id, // 成交的订单单号

                ];

                $orderInfo     = [       // 本次需要新增的订单金额

                    // 'order_amount' => $total_amount, // 本次订单金额

                    // 'order_time'   => $data['deal_time'],   // 本次订单的时间-时间戳

                ];

                // $member_products = 0; // 购买了几次会员商品

                $yhjOrderInfo  = [    // 本次需要处理的优惠卷

                    'yhj_id'     => isset($request['yhj_id'])?$request['yhj_id']:0,      // 本次优惠卷的id

                    'order_id'  => $order->id,   // 本次订单的id

                    'order_no'  => $data['order_no'],   // 本次订单的id

                    'operator_id' => $data['sale_id'],  // 核销人的id

                ];


                // echo "<pre>";
                // print_r($balanceData);
                // exit;

                $customerModel->processingFunds($customer_id,$balanceData,$request['deal_time'],$newOrderData,$orderInfo,$yhjOrderInfo,$member_products);

                // print_r($serviceDataAll);exit;

                $customerModel->addCustomService($customer_id,$serviceDataAll);

                // 生成出库记录
                $addLogModel = new AddOrderLog();

                $deal_time = strtotime($request['deal_time']);

                $addLogModel->addData($customer_id,$request['shop_id'],$order->order_no,$deal_time,'4');

                //处理成功，推送金蝶

                // exit;

                // 处理客户的余额 //

                // 客户推送金蝶
				//echo '1515';exit;


                if ($shop['type'] != 2)

                {

                    $res = $customerModel->pushKingCustomer($customer_id);

                    if($res == false){

                        $this->error = $customerModel->getError();

                        return false;

                    }

                    $kingDee = new Kingdee();

                    $result=$kingDee->send_order($order->id);

                    if ($result['code'])

                    {

                        $this->error = $result['msg'];

                        return false;

                    }

                }


                Db::commit();

                $this->error = '创建成功';

                return true;

            }

        } catch (\Exception $e) {

            Db::rollback();

            $this->error = $e->getMessage();

            return false;

        }

        $this->error = '创建失败';

        return false;

    }





    /**

     * 修改订单状态

     * 审核、反审核、作废、确认收货

     * @param array $request 请求参数

     * @return bool

     * @author Liu

     * @create 2021-11-08

     */

    public function checkOrderData($request)

    {

        // echo "作废销售出库单";
        // echo "<br/>";
        // exit;

        $id = $request['order_id'] ?? 0;

        $status = $request['status'] ?? 0;

        if (!$id) {

            $this->error = '参数错误';

            return false;

        }



        $order = Db::name('shop_order')->where('id',$id)->find();

        $goodList = Db::name('shop_order_goods')->where('order_id',$order['id'])->select()->toArray();

        // echo "<pre>";
        // print_r($goodList);
        // echo "</pre>";

        $vipCard = 0;
        foreach ($goodList as $key => $value) {
            if($value['kingdee_code'] == '101.12.099'){
                $vipCard = bcsub($vipCard,$value['number'],0);
            }
        }

        // echo $vipCard;
        // exit;

        $deal_time = date('Y-m-d',$order['deal_time']);

        if(!$order)

        {

            $this->error = '订单不存在';

            return false;

        }

        $content = '';

        // 订单反审核

        // 订单作废

        if($status !== 4)

        {

            $this->error = '订单状态不正确';

            return false;

        }





        try {

            $arr = [0=>'待支付',1=>'已支付',2=>'已下推',3=>'已评价',4=>'已作废'];

            $content .= '，状态：【' . $arr[$order['status']] . '】修改为【' . $arr[$status] . '】';



            $data['status'] = $status; // 订单状态： 订单状态：0.待支付 1.已支付 2.已下推 3.已评价 4.已取消

            $data['update_time'] = time();

            $bool = $this->where(['id'=>$id])->update($data);

            if ($bool !== false) {

                // 处理客户的余额 //

                $customerModel = new \app\crm\model\Customer();

                $customer_id   = $order['uid'];    // 客户的id

                $type = 1;

                $balanceData   = [                // 余额变更数据集

                    'change_type'  => $type,      // 变动类型 1:增加 2:减少

                    'change_money' => $order['pay_amount'],      // 变更的本金

                    'complimentary_money' => $order['gift_amount'],  // 变更的赠金

                    'balance_category_id' => $order['business_type'] // 变更的余额的类型 1:疤痕 2:项目

                ];

                $newOrderData  = [   // 新单变更数据集

                    // 'cj_time'  => ($data['type']==3 && $data['order_type']==1 && $total_amount>500)?$data['deal_time']:0,     // 成交时间-时间戳

                    // 'cj_money'    => $total_amount,    // 成交金额

                    // 'cj_order_id' => $order->id, // 成交的订单单号

                ];

                $orderInfo     = [       // 本次需要新增的订单金额

                    // 'order_amount' => $pay_price, // 本次订单金额

                    // 'order_time'   => $data['type']==3 ? $data['deal_time'] : 0,   // 本次订单的时间-时间戳

                ];

                $member_products = $vipCard; // 购买了几次会员商品

                $yhjOrderInfo  = [    // 本次需要处理的优惠卷

                    'yhj_id '     => 0,      // 本次优惠卷的id

                    'order_id  '  => 0,   // 本次订单的id

                    'operator_id' => 0,  // 核销人的id

                ];

                // exit;

                $customerModel->processingFunds($customer_id,$balanceData,$deal_time,$newOrderData,$orderInfo,$yhjOrderInfo,$member_products);

                // 添加操作记录

                $this->addActionRecord($request['operator_id'], 'shop_order_check', $id, $content, 'shop', 'order');

                $addLogModel = new AddOrderLog();

                $addLogModel->deletedData($customer_id,$order['order_no']);

                $this->error = '操作成功';

                return true;

            }

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return false;

        }

        $this->error = '操作失败';

        return false;

    }









    /**

     * 生成订单号

     * @param  array $request 请求参数

     * @return String

     * @author SL

     * @create 2021-06-03

     */

    public function getOrderNo()

    {

        $order_sn = null;

        // 保证不会有重复订单号存在

        while(true){

            $order_sn = date('YmdHis').rand(1000,9999); // 订单编号

            $order_sn_count = DB::name('shop_order')->where('order_no', $order_sn)->count();

            if($order_sn_count == 0)

                break;

        }

        return $order_sn;

    }





    /**

     * 订单操作记录

     * @param  array $request 请求参数

     * @return array

     * @author SL

     * @create 2021-06-10 9:33

     */

    public function getOrderRecordList(array $request): array

    {

        $orderId = $request['order_id'] ?? 0;

        if (!$orderId) {

            $this->error = '参数错误';

            return [];

        }



        $page  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;

        $limit = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;

        return $this->getActionRecordListByPage($orderId, 'shop', 'order', 0, $page, $limit);

    }





    /**

     * 获取订单列表

     * @param  array $request 请求参数

     * @return array

     * @author SL

     * @create 2021-06-1

     */

    public function lcokOrderData($request)

    {

        try {

            $userId  = $request['user_id'] ?? 0;

            $shopIds= $request['shopIds'] ?? '';

            $request = $this->fmtRequest($request);

            $map     = $request['map'] ?? [];

            $where   = [];

            $uid      = isset($map['uid']) && $map['uid'] ? trim($map['uid']) : ''; // 会员id

            $shop_id      = isset($map['shop_id']) && $map['shop_id'] ? trim($map['shop_id']) : ''; // 门店id

            $noValue      = isset($map['no_value']) && $map['no_value'] ? trim($map['no_value']) : ''; // 单号

            $consignee = isset($map['consignee']) && $map['consignee'] ? trim($map['consignee']) : ''; // 客户名称

            $start_time = isset($map['start_time']) && $map['start_time'] ? strtotime(date($map['start_time'])) : 0;

            $end_time = isset($map['end_time']) && $map['end_time'] ? strtotime(date($map['end_time'] . ' 23:59:59')) : 0;

            $business_type    = isset($map['business_type']) && intval($map['business_type']) ? intval($map['business_type']) : 0; // 订单状态

            $order_type       = isset($map['order_type']) && intval($map['order_type']) ? intval($map['order_type']) : 0; // 订单状态

            $low_total = isset($map['low_total']) && $map['low_total'] ? $map['low_total']: 0;//销售金额区间搜索最小值

            $large_total =  isset($map['large_total']) && $map['large_total'] ? $map['large_total']: 0;//销售金额区间搜索最大值

            $shop_name = isset($map['shop_name']) && $map['shop_name'] ? trim($map['shop_name']) : ''; // 门店名称

            // 获取客户数据权限 的客户名称

            if ($shopIds)

            {

                array_push($where, ['shop_id', 'in', $shopIds]);

            }

            if ($uid)

            {

                //会员id搜索

                array_push($where, ['uid', '=', $uid]);

            }

            if ($shop_id)

            {

                //门店id搜索

                array_push($where, ['shop_id', '=', $shop_id]);

            }



            if ($shop_name)

            {

                //门店名称搜索

                array_push($where, ['shop_name', 'like', '%'.$shop_name.'%']);

            }

            if ($consignee) {

                // 客户名称搜索

                array_push($where, ['consignee', 'like', '%'.$consignee.'%']);

            }

            if ($noValue) {

                array_push($where, ['order_no', '=', $noValue]);

            }





            // 时间

            if($start_time && $end_time)

            {

                array_push($where, ['deal_time', 'between', "$start_time,$end_time"]);

            }



            if ($business_type)

            {

                //业务类型搜索

                array_push($where, ['business_type', '=', $business_type]);

            }

            if ($order_type)

            {

                //订单类型搜索

                array_push($where, ['order_type', '=', $order_type]);

            }



            if ($low_total && !$large_total)

            {

                array_push($where, ['order_amount', 'egt', $low_total]);

            }

            if (!$low_total && $large_total)

            {

                array_push($where, ['order_amount', 'elt', $large_total]);

            }

            if ($low_total && $large_total)

            {

                array_push($where, ['order_amount', 'between', "$low_total,$large_total"]);

            }

            $sqlQuery = $this->where($where);

            $dataCount  = $sqlQuery->count();

            $bool=0;

            if ($dataCount) {

                $bool = $sqlQuery->update(['is_lock' => 1]);

            }

            $this->error = '锁定成功'.$bool.'单';

            $data              = [];

            $data['dataCount'] = $bool ?? 0;

            return $data;

        } catch (\Exception $e) {

            $this->error = $e->getMessage();

            return [];

        }

    }









}

